//
//  HomeViewController.m
//  shise
//
//  Created by 毛志鹏 on 14/12/17.
//  Copyright (c) 2014年 MZP. All rights reserved.
//

#import "HomeViewController.h"
#import "DetailViewController.h"
#import "UserDetailViewController.h"
#import "CrossSlipDetailViewController.h" // 活动详情界面
#import "ActivityCell.h"
#import "MoreDetailCell.h"
#import "NetHandler.h"
#import "Activity.h"
#import "Food.h"
#import "FoodList.h"
#import "DataBaseHaneler.h"
#import "MJRefresh.h"
#import "Reachability.h"
#import "MBProgressHUD.h"


@interface HomeViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *foodArr; // 美食数组
@property (nonatomic, retain) NSMutableArray *ActivityArr; // 活动数组
@property (nonatomic, retain) NSMutableArray *foodListArr; // 食单数组
@property (nonatomic, retain) NSString *refresh; // 刷新时用的API
@property(nonatomic, retain)MBProgressHUD *noHUD;


@end

@implementation HomeViewController

// 内存释放
- (void)dealloc
{
    [_tableView release];
    [_foodArr release];
    [_ActivityArr release];
    [_foodListArr release];
    [_refresh release];
    [super dealloc];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    [self.view addSubview: self.tableView];
    
    self.view.userInteractionEnabled = NO;
    
    // 去掉纵向滚动条
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 去掉表格分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView release];
    
    // 评论不要了
//    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(clickComment)];
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSLog(@"新浪用户名%@", [user objectForKey:@"userName"]);
//    NSLog(@"新浪用户头像%@", [user objectForKey:@"userAvatar"]);
    
    
//    [self handleAct];
    // 处理数据
//    [self handleData];
    
    // 执行刷新
    [self setupRefresh];
    
    // 隐藏导航栏和tabBar
    [self followRollingScrollView:self.tableView];
    
}

// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        return 170;
        
    } else {
        
        return 410;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    // cell 的高度问题  都在这个方法中写
//    // 1. 取数据
//    NSString *content = [[self.foodArr objectAtIndex:indexPath.row] content];
//    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
//    // 2. 通过字符串的内容, 计算在一定宽度下文本占用的高度
//    // 参数1: 通过CGSize 给定一个高度, 用来计算
//    // 参数2: 通过一个行为矩形, 计算高度
//    // 参数3: 计算时依照的字体大小 字典类型
//    // 参数4:
//    CGRect rect = [content boundingRectWithSize:CGSizeMake(tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
//    
//    return rect.size.height + 400;
//    
//}

// 点击cell的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 点击后还原颜色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    FoodDetailViewController *foodDetail = [[FoodDetailViewController alloc] init];
//    foodDetail.food = [self.foodArr objectAtIndex:indexPath.row - 1];
//    [self.navigationController pushViewController:foodDetail animated:YES];
//    [foodDetail release];
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    self.tableView.headerRefreshingText = @"正在刷新...";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在刷新...";
    
}
// 下拉刷新
- (void)headerRereshing
{
    [self handleAct];
    [self handleData];
        
        // 2.2秒后刷新表格UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
            
            self.view.userInteractionEnabled = YES;
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView headerEndRefreshing];
        });
}
// 上啦加载
- (void)footerRereshing
{
    NSString *str = self.refresh;
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
        
        NSArray *arr = [result objectForKey:@"data"];
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
        
        // 新建一个数组用来存放上拉刷新后 请求的美食对象
        NSMutableArray *newFoodArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Food *food = [[Food alloc] initWithDictionary:dic];
            [newFoodArr addObject:food];
            [food release];
        }
        [self.foodArr addObjectsFromArray:newFoodArr];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        });
        
    }];
    
}


// 处理数据的方法
- (void)handleData
{
    NSString *str = @"https://api.shiseapp.com/v2/timeline/";
    //    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
        
        NSArray *arr = [result objectForKey:@"data"];
        // 刷新时用的API
        
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
        //        NSLog(@"刷新API : %@", self.refresh);
        
        // 对数据源初始化
        self.ActivityArr = [NSMutableArray array];
        self.foodArr = [NSMutableArray array];
//        self.foodListArr = [NSMutableArray array];
        
        // 由于接口变化, 单独写活动数据处理方法
        [self handleAct];
        
        for (NSDictionary *tempDic in arr) {
            
//            if ([[tempDic objectForKey:@"type"] isEqualToString:@"EventCard"]) {
//                Activity *activity = [[Activity alloc] initWithDictionary:tempDic];
//                [self.ActivityArr addObject:activity];
//                [activity release];
//                
//            } else if ([[tempDic objectForKey:@"type"] isEqualToString:@"PicCard"]) {
//                FoodList *foodlist = [[FoodList alloc] initWithDictionary:tempDic];
//                [self.foodListArr addObject:foodlist];
//                [foodlist release];
//                
//            } else
                if ([[tempDic objectForKey:@"type"] isEqualToString:@"MediaCard"]) {
                Food *food = [[Food alloc] initWithDictionary:tempDic];
                [self.foodArr addObject:food];
                [food release];
            }
        }
        // 重新加载数据
        [self.tableView reloadData];
    }];

}

// 处理"活动"的方法
- (void)handleAct
{
    NSString *strss = @"https://api.shiseapp.com/v2/timeline/event/103/?";
    [NetHandler getDataWithUrl:strss completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
//        NSLog(@"%@", result);
        
        NSArray *arr = [result objectForKey:@"data"];
        NSDictionary *tempDic = [[NSDictionary alloc] initWithDictionary:[arr objectAtIndex:0]];
        Activity *activity = [[Activity alloc] initWithDictionary:tempDic];
        [self.ActivityArr addObject:activity];
        [activity release];
        [tempDic release];
//        NSLog(@"我新处理的活动对象 :::: %@", activity);
        [self.tableView reloadData];
    }];

}


// tableView 两个代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.foodArr.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        ActivityCell *actCell = [tableView dequeueReusableCellWithIdentifier:@"activity"];
        
        if (actCell == nil) {
            actCell = [[[ActivityCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"activity"]autorelease];
        }
        actCell.actImageButton.tag = 1111;
        [actCell.actImageButton addTarget:self action:@selector(clickAct:) forControlEvents:UIControlEventTouchUpInside];
        if (self.ActivityArr.count > 0) {
        
            Activity *activity = [self.ActivityArr objectAtIndex:indexPath.row];
            actCell.activity = activity;
            
        }
        return actCell;
    } else {
        MoreDetailCell *foodCell = [tableView dequeueReusableCellWithIdentifier:@"food"];
        if (foodCell == nil) {
            foodCell = [[[MoreDetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"food"]autorelease];
        }
        // 左上角 "精" 字样
        UIImageView *jing = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 25, 25)];
        jing.image = [UIImage imageNamed:@"iconfont-sanjiao.png"];
        [foodCell addSubview:jing];
        [jing release];
        
        UIImageView *jingW = [[UIImageView alloc] initWithFrame:CGRectMake(3, 3, 9, 9)];
        jingW.image = [UIImage imageNamed:@"iconfont-jing.png"];
        [jing addSubview:jingW];
        [jingW release];
        
        
        // 为cell上的按钮添加点击跳转详情的方法
        
        foodCell.foodImageViewButton.tag = 10000 + indexPath.row;
        [foodCell.foodImageViewButton addTarget:self action:@selector(clickPic:) forControlEvents:UIControlEventTouchUpInside];
        
        foodCell.userHeadImageViewButton.tag = 20000 + indexPath.row;
        [foodCell.userHeadImageViewButton addTarget:self action:@selector(clickHead:) forControlEvents:UIControlEventTouchUpInside];
        
        foodCell.praiseImageViewButton.tag = 30000 + indexPath.row;
        [foodCell.praiseImageViewButton addTarget:self action:@selector(clickPraise:) forControlEvents:UIControlEventTouchUpInside];
        
        foodCell.markImagViewButton.tag = 40000 + indexPath.row;
        [foodCell.markImagViewButton addTarget:self action:@selector(clickMark:) forControlEvents:UIControlEventTouchUpInside];
        
        Food *food = [self.foodArr objectAtIndex:indexPath.row - 1];
        foodCell.food = food;
        
        if (food.clickPraiseCount % 2 == 0) {
            
            foodCell.praiseImageView.image = [UIImage imageNamed:@"praiseFont.png"];
        } else {
            
            foodCell.praiseImageView.image = [UIImage imageNamed:@"praiseBehind.png"];
        }
        if (food.clickMarkCount != 0) {
            
            foodCell.markImageView.image = [UIImage imageNamed:@"markBehind.png"];
        } else {
            
            foodCell.markImageView.image = [UIImage imageNamed:@"mark.png"];
        }

        return foodCell;
    }
    
}


// 点击活动跳转详情
- (void) clickAct:(UIButton *)button
{
    [self showNavi];
    
    CrossSlipDetailViewController *actDetail = [[CrossSlipDetailViewController alloc] init];
    
    actDetail.address = @"/v2/timeline/event/103/?";
    
    [self.navigationController pushViewController:actDetail animated:YES];
    [actDetail release];
    
}

// 点击图片跳转详情
- (void) clickPic:(UIButton *)foodPic
{
    
    [self showNavi];
    
    DetailViewController *foodDetail = [[DetailViewController alloc] init];
    
    foodDetail.detailApi = [[self.foodArr objectAtIndex:foodPic.tag - 10000 - 1] objId];
    
    foodDetail.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:foodDetail animated:YES];
    [foodDetail release];
}
// 点击头像跳转用户详情
- (void) clickHead:(UIButton *)userHead
{
    [self showNavi];
    
    UserDetailViewController *userDetail = [[UserDetailViewController alloc] init];
    
    Food *temp = [self.foodArr objectAtIndex:userHead.tag - 20000 - 1];
    
    userDetail.userApi = [temp.user objectForKey:@"id"];
    
    userDetail.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:userDetail animated:YES];
    [userDetail release];
}
// 点击“赞”的时候执行的方法
- (void)clickPraise:(UIButton *)button
{
    
    // 当点击赞的时候赞的图片变成红色的同时赞的人数加1
    NSInteger numberOfCell = button.tag - 30000 - 1;
    Food *food = [self.foodArr objectAtIndex:numberOfCell];
    if (food.clickPraiseCount % 2 == 0) {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew + 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", (long)likeCountNew];
        //        self.number = 1;
        [self.tableView reloadData];
        
    } else {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew - 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", (long)likeCountNew];
//        self.number = 1;
        [self.tableView reloadData];
    }
}

// 点击“马克”的时候执行的方法
- (void)clickMark:(UIButton *)button
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    if ([def objectForKey:@"userName"] == nil) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];

    } else {
        
        NSInteger numberOfCell = button.tag - 40000 - 1;
        Food *food = [self.foodArr objectAtIndex:numberOfCell];
        food.clickMarkCount += 1;
        [self.tableView reloadData];
        NSDictionary *dic = food.user;
        // 将用户信息字典中的用户头像地址取出来赋值给用户头像地址 字符串
        food.userHeadeImageViewAddress = [dic objectForKey:@"avatar"];
        NSLog(@"人物头像地址%@", food.userHeadeImageViewAddress);
        
        // 当收藏本条美食信息的时候就讲本条没事信息存储到本地 当点击我的收藏的时候从本地读取信息 并显示
        DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
        // 打开数据库
        [handler openDB];
        // 创建美食表表
        [handler createFoodTable];
        // 添加一条美食数据
        [handler insertFood:food userName:[def objectForKey:@"userName"]];
        
    }
}

// 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    if ([self GetCurrntNet]) {
        [self handleData];
        
    }
    else {
        /// 缓冲
//        NSLog(@"没有网络");
        self.noHUD = [[MBProgressHUD alloc]initWithView:self.view];
        [self.noHUD setMode:MBProgressHUDModeIndeterminate];
        self.noHUD.labelText = @"网络不可用,请检查";
        [self.noHUD show:YES];
        [self performSelector:@selector(removeNoHUDView) withObject:self afterDelay:2];
        [self.view addSubview:_noHUD];
        [_noHUD release];
    }
    [self.tableView reloadData];
    
}

-(NSString*) GetCurrntNet
{
    NSString* result;
    Reachability *r = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:     // 没有网络连接
            result=nil;
            break;
        case ReachableViaWWAN: // 使用3G网络
            result=@"3g";
            break;
        case ReachableViaWiFi: // 使用WiFi网络
            result=@"wifi";
            break;
    }
    return result;
}

-(void)removeNoHUDView
{
    [self.noHUD removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
